import { DetailedHTMLProps, ImgHTMLAttributes, useEffect, useRef, useState } from 'react'

interface LazyLoadProps extends DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement> {
  
}

export default function LazyLoad(props: LazyLoadProps) {
  const {src = '', ...other} = props
  const [URL, setURL] = useState('')
  const img = useRef(null)

  useEffect(() => {
    var io = new IntersectionObserver((entries) => {
      // @ts-ignore
      if (entries[0].intersectionRatio > 0) {
        setURL(src)
        img.current && io.unobserve(img.current)
      }
    }, {})   

    if (img.current) {
      io.observe(img.current)
    }
  }, [])
  return (
    <img ref={img} src={URL} {...other} />
  )
}